package com.andryu.base.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import com.andryu.base.R
import com.andryu.base.constant.CommonConstants
import com.andryu.base.entity.LearnListEntity

class LearnListAdapter(private val dataList:MutableList<LearnListEntity>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var mListener: ((entity: LearnListEntity) -> Unit?)? = null

    fun setOnItemClick(listener:(entity: LearnListEntity) -> Unit){
        mListener = listener
    }

    override fun getItemViewType(position: Int): Int {
        return dataList[position].type
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when(viewType){
            CommonConstants.LEARN_INFO_TITLE -> ViewHolderTitle(
                LayoutInflater.from(parent.context).inflate(R.layout.item_learn_title, parent, false)
            )
            CommonConstants.LEARN_INFO_CONTENT ->ViewHolderContent(
                LayoutInflater.from(parent.context).inflate(R.layout.item_learn_content, parent, false)
            )
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    override fun getItemCount(): Int = dataList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val entity = dataList[position]
        when(holder.itemViewType){
            CommonConstants.LEARN_INFO_TITLE -> (holder as ViewHolderTitle).bind(entity)
            CommonConstants.LEARN_INFO_CONTENT -> (holder as ViewHolderContent).bind(entity)
        }
    }

    inner class ViewHolderTitle(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val mItemName: AppCompatTextView = itemView.findViewById(R.id.tv_item_title)

        fun bind(data: LearnListEntity){
            mItemName.text = data.name
        }
    }

    inner class ViewHolderContent(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val mItemName: AppCompatTextView = itemView.findViewById(R.id.tv_item_title)
        private val mItemContent:AppCompatTextView = itemView.findViewById(R.id.tv_item_content)
        fun bind(data: LearnListEntity){
            mItemName.text = data.name
            mItemContent.text = data.info
            itemView.setOnClickListener {
                mListener?.invoke(data)
            }
        }
    }
}